package com.wmh.baseservice.skd.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.HashSet;
import java.util.Set;

/**
 * 校验团购活动参数数据格式是否有效
 */
@Slf4j
public class VerifyGroupBuyingActivityParams {
    private static final Set<String> ALLOWED_CONTENT_TYPES = new HashSet<>();

    static {
        ALLOWED_CONTENT_TYPES.add("bigPicture");
        ALLOWED_CONTENT_TYPES.add("smallPictures");
        ALLOWED_CONTENT_TYPES.add("video");
        ALLOWED_CONTENT_TYPES.add("labels");
        ALLOWED_CONTENT_TYPES.add("word");
        ALLOWED_CONTENT_TYPES.add("wechatFanCard");
        ALLOWED_CONTENT_TYPES.add("serviceCommitment");
    }

    /**
     * 判断是否为有效团购活动内容数据格式
     *
     * @param json json格式字符串
     * @return 返回是否有效
     */
    public static boolean isValidContent(String json) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonArray = objectMapper.readTree(json);

            if (!jsonArray.isArray()) {
                throw new IllegalArgumentException("输入必须是一个 JSON 数组");
            }

            int lastElementIndex = jsonArray.size() - 1;

            if (lastElementIndex >= 0) {
                for (int i = 0; i < lastElementIndex; i++) {
                    validateElement(jsonArray.get(i));
                }

                JsonNode lastElement = jsonArray.get(lastElementIndex);
                validateServiceCommitment(lastElement);

                int serviceCommitmentCount = countElementsWithContentType(jsonArray, "serviceCommitment");
                int labelsCount = countElementsWithContentType(jsonArray, "labels");

                if (serviceCommitmentCount > 1) {
                    throw new IllegalArgumentException("只允许使用一个 serviceCommitment 元素");
                }

                if (labelsCount > 1) {
                    throw new IllegalArgumentException("只允许使用一个 labels 元素");
                }

            } else {
                throw new IllegalArgumentException("JSON 数组不得为空");
            }

            return true;
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    private static void validateElement(JsonNode element) {
        if (element.has("contentType") && element.has("value")) {
            String contentType = element.get("contentType").asText();

            if (!ALLOWED_CONTENT_TYPES.contains(contentType)) {
                throw new IllegalArgumentException("无效的内容格式: " + contentType);
            }

            switch (contentType) {
                case "bigPicture":
                case "video":
                case "word":
                    if (!element.get("value").isTextual()) {
                        throw new IllegalArgumentException(contentType + "必须为文本格式");
                    }
                    break;
                case "smallPictures":
                    if (!element.get("value").isArray()) {
                        throw new IllegalArgumentException("小图字段数据必须为数组格式");
                    }
                    for (JsonNode value : element.get("value")) {
                        if (!value.isTextual()) {
                            throw new IllegalArgumentException("小图字段数据必须为文本格式");
                        }
                    }
                    break;
                case "labels":
                    if (!element.get("value").isTextual()) {
                        throw new IllegalArgumentException("标签字段数据必须为文本格式");
                    }
                    break;
                case "wechatFanCard":
                    if (!element.get("value").isObject()) {
                        throw new IllegalArgumentException("微信加粉卡片字段数据必须为对象格式");
                    }
                    // 如有需要，为微信名片内的字段添加进一步验证
                    break;
            }
        } else {
            throw new IllegalArgumentException("每个元素必须有 contentType 和 value 字段");
        }
    }

    private static void validateServiceCommitment(JsonNode element) {
        if (element.has("contentType") && element.has("value")) {
            String contentType = element.get("contentType").asText();
            if (!"serviceCommitment".equals(contentType)) {
                throw new IllegalArgumentException("服务承诺字段数据必须在元素末尾");
            }

            if (!element.get("value").isObject()) {
                throw new IllegalArgumentException("服务承诺字段数据必须为对象格式");
            }
            // 必要时为 serviceCommitment 内的字段添加进一步验证
        } else {
            throw new IllegalArgumentException("最后一个元素必须有 contentType 和 value 字段");
        }
    }

    private static int countElementsWithContentType(JsonNode jsonArray, String contentType) {
        int count = 0;

        for (JsonNode element : jsonArray) {
            if (element.has("contentType") && element.get("contentType").asText().equals(contentType)) {
                count++;
            }
        }

        return count;
    }

    /**
     * 判断是否为有效奖金数据格式
     * @param jsonString json格式字符串
     * @param bonusType 奖金类型
     * @return 返回是否有效
     */
    public static boolean isValidBonus(String jsonString, String bonusType) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonString);

            if (jsonNode.isArray()) {
                for (JsonNode item : jsonNode) {
                    if (!item.isObject()) {
                        return false;
                    }

                    if ("commissionSettings".equals(bonusType)) {
                        if (!item.has("volume") || !item.has("commissionPerItem")) {
                            return false;
                        }

                        if (!item.get("volume").isNumber() || !item.get("commissionPerItem").isNumber()) {
                            return false;
                        }
                    } else if ("volumeRewardSettings".equals(bonusType)) {
                        if (!item.has("volume") || !item.has("reward")) {
                            return false;
                        }

                        if (!item.get("volume").isNumber() || !item.get("reward").isNumber()) {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
                return true;
            }

            return false;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 判断是否为有效的同城配送数据格式
     * @param jsonString json格式字符串
     * @return 返回是否有效
     */
    public static boolean isValidCityDelivery(String jsonString) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonString);

            if (jsonNode.isObject()) {
                JsonNode basicShippingFeeNode = jsonNode.get("basicShippingFee");

                if (basicShippingFeeNode != null && basicShippingFeeNode.isObject()) {
                    JsonNode deliveryNoteNode = basicShippingFeeNode.get("deliveryNote");
                    JsonNode fixedShippingFeeNode = basicShippingFeeNode.get("fixedShippingFee");

                    return deliveryNoteNode != null && fixedShippingFeeNode != null &&
                            deliveryNoteNode.isTextual() && fixedShippingFeeNode.isNumber();
                }
            }

            return false;
        } catch (Exception e) {
            return false;
        }
    }

}
